//import GetToken from "./token.js";

// Token.get_token();

let baseUrl = "http://127.0.0.1:8000/api";

class HTTP {
  
  request({ url, method, data = {}, requireAuth=false}){
    return new Promise((resolve,reject)=>{
      this._request(url, resolve, reject, method,data,requireAuth) 
    });
  }
  
  _request(url, resolve, reject, method, data, requireAuth){

    let header = { "content-type": "application/json" };

    if(requireAuth){
      
      let token = wx.getStorageSync("token");
       
       if(!token){     
         wx.navigateTo({
           url: '/pages/about/about'
         })
         return false;
       }

      // header.token = token;
      header.Authorization = 'Bearer ' + token;
       
    }
    
    if (!method) {
      method = "GET";
    }
    
    wx.request({
      url: baseUrl+url,
      method,
      header,
      data,
      success(res){
         
         // 登录过期处理
        if (res.statusCode  == '401'){

           wx.showToast({
             title: '登录过期，请重新登录',
             icon:'none',
             duration: 2000,
             success(){
                
                // 延迟切换到登录页
                setTimeout(function(){
                    wx.navigateTo({
                      url: '/pages/login/login'
                    })
                },2000)
                
             }
           })
           
           
         }else{
            resolve(res);
         }

      }

    })

  }

  // 登录验证;
  checkLogin(){

    // 获取登录状态
    let is_login = wx.getStorageSync('is_login');
    let msg = "";
    
    // 判断是否在有效期内; 
    if(is_login){

      let expires_in = wx.getStorageSync('expires_in');
     
      let t1 = new Date().getTime();
      let t2 = new Date(expires_in).getTime();
      if(t2>t1){
        let jsonStr = wx.getStorageSync("user");
        return JSON.parse(jsonStr);
      }else{
         msg = "登录过期，请重新登录!";         
      }

    }else{
       msg = "请先登录!"
    }

    // 未登录 或登录过期，跳转到登录页;

    wx.showToast({
      title: msg,
      icon:"none",
      success(){
         setTimeout(function(){
            wx.navigateTo({
              url: '/pages/login/login',
            })
         },1500)
      }
    })
  
 
  } 

  
}

export default  new HTTP();